import {
  Provide,
  Inject,
  CommonSchedule,
  TaskLocal,
  FORMAT,
} from '@midwayjs/core';
import { ILogger } from '@midwayjs/logger';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { DeviceDeviceEntity } from '../device/entity/device';

/**
 * 数据定时清除定时任务
 */
@Provide()
export class BaseMqttSchedule implements CommonSchedule {
  @Inject()
  logger: ILogger;

  @InjectEntityModel(DeviceDeviceEntity)
  DeviceDeviceEntity: Repository<DeviceDeviceEntity>;

  // 定时执行的具体任务
  //   @TaskLocal(FORMAT.CRONTAB.EVERY_SECOND)
  async exec() {
    /* 遍历device表，判断最后在线时间是否超过120秒，如果超出，则修改其状态为2 */
    const devices = await this.DeviceDeviceEntity.find();

    for (const device of devices) {
      if (
        device.lastOnlineTime &&
        device.lastOnlineTime + 180 < Date.now() / 1000
      ) {
        device.deviceStatus = 2;
        await this.DeviceDeviceEntity.save(device);
      }
    }
  }
}
